from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Boolean, Numeric
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from ..base import Base


class Product(Base):
    """
    商品模型
    """
    __tablename__ = "products"

    id = Column(Integer, primary_key=True, index=True, comment="商品ID")
    name = Column(String(200), nullable=False, comment="商品名称")
    description = Column(Text, nullable=True, comment="商品描述")
    price = Column(Numeric(10, 2), nullable=False, comment="商品价格")
    original_price = Column(Numeric(10, 2), nullable=True, comment="原价")
    stock = Column(Integer, default=0, comment="库存数量")
    sales = Column(Integer, default=0, comment="销量")
    category_id = Column(Integer, ForeignKey("product_categories.id"), nullable=False, comment="商品分类ID")
    image_url = Column(String(500), nullable=True, comment="商品图片URL")
    sku = Column(String(100), unique=True, nullable=False, comment="商品SKU")
    is_active = Column(Boolean, default=True, comment="是否上架")
    is_featured = Column(Boolean, default=False, comment="是否推荐商品")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关联分类
    category = relationship("ProductCategory", backref="products")

    def __repr__(self):
        return f"<Product(id={self.id}, name='{self.name}', price={self.price})>"